import 'package:flutter/material.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/services.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:loxen/viewmode/login_view_model.dart';
import 'package:loxen/widget/my_subassembly.dart';
import 'package:provider/provider.dart';
import 'package:loxen/dialog/toast.dart';

class ModifyPasswordWidget extends StatefulWidget {
  @override
  _ModifyPasswordWidgetState createState() => _ModifyPasswordWidgetState();
}

class _ModifyPasswordWidgetState extends State<ModifyPasswordWidget> {
  //焦点
  FocusNode _focusNodePwd = new FocusNode();
  FocusNode _focusNodeNewPassWord = new FocusNode();
  FocusNode _focusNodeNotarizePassWord = new FocusNode();

  //用户名输入框控制器，此控制器可以监听用户名输入框操作
  TextEditingController _userPwdController = new TextEditingController();
  TextEditingController _userNewPwdController = new TextEditingController();
  TextEditingController _userNotarizePwdController =
      new TextEditingController();

  //表单状态
  GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  var _isShowPwd = false; //是否显示原密码
  var _isShowNewPwd = false; //是否显示新密码
  var _isShowNotarizePwd = false; //是否显示确认密码
  var _isShowClear = false; //是否显示输入框尾部的
  var _isShowClearPwd = false; //是否显示输入框尾部的
  var _isShowClearNotarizePwd = false; //是否显示输入框尾部的

  @override
  void initState() {
    // TODO: implement initState
    //设置焦点监听
    _focusNodePwd.addListener(_focusNodeListener);
    _focusNodeNewPassWord.addListener(_focusNodeListener);
    _focusNodeNotarizePassWord.addListener(_focusNodeListener);
    //监听用户名框的输入改变
    _userPwdController.addListener(() {
      print(_userPwdController.text);

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userPwdController.text.length > 0) {
        _isShowClear = true;
      } else {
        _isShowClear = false;
      }
      setState(() {});
    });
    _userNewPwdController.addListener(() {
      print(_userNewPwdController.text);

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNewPwdController.text.length > 0) {
        _isShowClearPwd = true;
      } else {
        _isShowClearPwd = false;
      }
      setState(() {});
    });
    _userNotarizePwdController.addListener(() {
      print(_userNotarizePwdController.text);

      // 监听文本框输入变化，当有内容的时候，显示尾部清除按钮，否则不显示
      if (_userNotarizePwdController.text.length > 0) {
        _isShowClearNotarizePwd = true;
      } else {
        _isShowClearNotarizePwd = false;
      }
      setState(() {});
    });
    super.initState();
  }

  @override
  void dispose() {
    // 移除焦点监听
    _focusNodePwd.removeListener(_focusNodeListener);
    _focusNodeNewPassWord.removeListener(_focusNodeListener);
    _focusNodeNotarizePassWord.removeListener(_focusNodeListener);
    _userPwdController.dispose();
    _userNewPwdController.dispose();
    _userNotarizePwdController.dispose();

    super.dispose();
  }

  // 监听焦点
  Future<Null> _focusNodeListener() async {
    if (_focusNodePwd.hasFocus) {
      print("用户名框获取焦点");
      // 取消密码框的焦点状态
      errname = null;
      _focusNodeNewPassWord.unfocus();
      _focusNodeNotarizePassWord.unfocus();
    }
    if (_focusNodeNewPassWord.hasFocus) {
      print("密码框获取焦点");
      // 取消用户名框焦点状态
      (_formKey.currentState as FormState).reset();

      _focusNodePwd.unfocus();
      _focusNodeNotarizePassWord.unfocus();
    }
    if (_focusNodeNotarizePassWord.hasFocus) {
      print("密码框获取焦点");
      // 取消用户名框焦点状态
      (_formKey.currentState as FormState).reset();

      _focusNodePwd.unfocus();
      _focusNodeNewPassWord.unfocus();
    }
  }

  /**
   * 验证密码
   */
  String validateUserPwd(value) {
    if (value.isEmpty) {
      return '密码不能为空!';
    } else if (value.length < 6) {
      return "密码不能少于6位";
    }
    return null;
  }

  String validateChangePwd(value) {
    if (value.isEmpty) {
      return '新密码不能为空';
    } else if (_userNewPwdController.text != _userNotarizePwdController.text) {
      return "两次密码不一致";
    }
    return null;
  }

  var errname;

  // TODO 加弹窗
  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          centerTitle: true,
          title: Text(
            "修改密码",
            style: TextStyle(
              color: Colors.black,
              fontSize: 32.sp,
            ),
          ),
          actions: <Widget>[
            Text(
              "修改密码",
            )
          ],
          backgroundColor: Colors.white,
          elevation: 0,
          leading: MySubassembly.getBackIcon(context, color: Colors.black),
        ),
        body: Container(
          decoration: BoxDecoration(
            border: Border(top: BorderSide(
                width: 1.h,
                color: Color(0xFFEBECF1)
            )),
            color: Theme.of(context).backgroundColor,
          ),
          child: GestureDetector(
            behavior: HitTestBehavior.opaque,
            onPanStart: (_) {
              FocusScope.of(context).requestFocus(FocusNode());
            },
            child: Stack(
              children: <Widget>[
                Padding(
                  padding: EdgeInsets.fromLTRB(36.w, 0.h, 34.w, 200.h),
                  child: Form(
                    key: _formKey,
                    child: Column(
                      children: <Widget>[
                        new TextFormField(
                          style: TextStyle(color: Colors.black),
                          obscureText: !_isShowPwd,
                          controller: _userPwdController,
                          focusNode: _focusNodePwd,
                          inputFormatters: [
                            LengthLimitingTextInputFormatter(18),
                          ],
                          decoration: InputDecoration(
                            errorText: errname,
                            errorStyle: TextStyle(
                                color: Color(0xFFFE0600), fontSize: 20.sp),
                            prefixIcon: Builder(
                                builder: (context) => FlatButton(
                                  child: Container(
                                    width: 120.w,
                                    child: Text(
                                      "原密码",
                                      style: TextStyle(
                                          fontSize: 26.sp,
                                          color: Color(0xFF000000)),
                                    ),
                                  ),
                                  onPressed: null,
                                )),

                            hintText: "填写原密码",
                            hintStyle: TextStyle(
                                fontSize: 26.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                            suffixIcon: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                (_isShowClear)
                                    ? SizedBox(
                                  height: 18.0,
                                  width: 18.0,

                                  child: IconButton(
                                    padding: EdgeInsets.all(0),
                                    icon: Icon(
                                      Icons.cancel,
                                      size: 27.sp,
                                    ),
                                    onPressed: () {
                                      // 清空输入框内容
                                      _userPwdController.clear();
                                    },
                                  ),)
                                    : Text(""),
                                Builder(
                                    builder: (context) => IconButton(padding: EdgeInsets.all(0),
                                      iconSize: 30.sp,
                                      icon: Icon((_isShowPwd)
                                          ? Icons.visibility
                                          : Icons.visibility_off),
                                      onPressed: () {
                                        setState(() {
                                          _isShowPwd = !_isShowPwd;
                                        });
                                      },
                                    ))
                              ],
                            ),
                          ),
                          validator: validateUserPwd,
                        ),
                        new TextFormField(
                            style: TextStyle(color: Colors.black),
                            controller: _userNewPwdController,
                            obscureText: !_isShowNewPwd,
                            focusNode: _focusNodeNewPassWord,
                            inputFormatters: [
                              LengthLimitingTextInputFormatter(18),
                            ],
                            decoration: InputDecoration(
                              errorStyle:
                              TextStyle(color: Colors.red, fontSize: 20.sp),
                              prefixIcon: Builder(
                                  builder: (context) => FlatButton(
                                    child: Container(
                                      width: 120.w,
                                      child: Text(
                                        "新密码",
                                        style: TextStyle(
                                            fontSize: 26.sp,
                                            color: Color(0xFF000000)),
                                      ),
                                    ),
                                    onPressed: null,
                                  )),

                              hintText: "6-18为数字或字母",
                              hintStyle: TextStyle(
                                  fontSize: 26.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                              suffixIcon: Row(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  (_isShowClearPwd)
                                      ? SizedBox(
                                    height: 18.0,
                                    width: 18.0,

                                    child: IconButton(
                                      padding: EdgeInsets.all(0),
                                      icon: Icon(
                                        Icons.cancel,
                                        size: 27.sp,
                                      ),
                                      onPressed: () {
                                        // 清空输入框内容
                                        _userNewPwdController.clear();
                                      },
                                    ),
                                  )
                                      : Text(""),
                                  Builder(
                                      builder: (context) => IconButton(
                                        iconSize: 30.sp,
                                        icon: Icon((_isShowNewPwd)
                                            ? Icons.visibility
                                            : Icons.visibility_off),
                                        onPressed: () {
                                          setState(() {
                                            _isShowNewPwd = !_isShowNewPwd;
                                          });
                                        },
                                      ))
                                ],
                              ),
                            ),
                            validator: validateUserPwd),
                        new TextFormField(
                          style: TextStyle(color: Colors.black),
                          obscureText: !_isShowNotarizePwd,
                          controller: _userNotarizePwdController,
                          focusNode: _focusNodeNotarizePassWord,
                          decoration: InputDecoration(
                            errorStyle:
                            TextStyle(color: Colors.red, fontSize: 20.sp),

                            prefixIcon: Builder(
                                builder: (context) => FlatButton(
                                  child: Container(
                                    width: 120.w,
                                    child: Text(
                                      "确认密码",
                                      style: TextStyle(
                                          fontSize: 26.sp,
                                          color: Color(0xFF000000)),
                                    ),
                                  ),
                                  onPressed: null,
                                )),

                            hintText: "再次填写新密码",
                            hintStyle: TextStyle(
                                fontSize: 26.sp, color: Color(0xFF999999)),
//                        尾部添加清除按钮
                            suffixIcon: Row(
                              mainAxisSize: MainAxisSize.min,
                              children: <Widget>[
                                (_isShowClearNotarizePwd)
                                    ? SizedBox(
                                  width: 18.0,
                                  height: 18.0,
                                  child: IconButton(
                                    padding: EdgeInsets.all(0),
                                    icon: Icon(
                                      Icons.cancel,
                                      size: 27.sp,
                                    ),
                                    onPressed: () {
                                      // 清空输入框内容
                                      _userNotarizePwdController.clear();
                                    },
                                  ),
                                )
                                    : Text(""),
                                Builder(
                                    builder: (context) => IconButton(
                                      iconSize: 30.sp,
                                      icon: Icon((_isShowNotarizePwd)
                                          ? Icons.visibility
                                          : Icons.visibility_off),
                                      onPressed: () {
                                        setState(() {
                                          _isShowNotarizePwd =
                                          !_isShowNotarizePwd;
                                        });
                                      },
                                    ))
                              ],
                            ),
                          ),
                          validator: validateChangePwd,
                        ),
                      ],
                    ),
                  ),
                ),
                Positioned(
                  top: 893.h,
                  left: 92.w,
                  child: Container(
                      width: 559.w,
                      height: 96.h,
                      color: Color(0xFF0CABCB),
                      child: Builder(
                        builder: (context) => FlatButton(
                          child: Text(
                            "保存",
                            style: TextStyle(
                                fontSize: 30.sp, color: Color(0xFFF7F8F8)),
                          ),
                          onPressed: () {
                            if ((_formKey.currentState).validate()) {
                              context.read<LoginViewModel>().password(
                                  _userPwdController.text,
                                  _userNotarizePwdController.text, onSuccess: () {
                                Navigator.pop(context);
                                Toast.show('修改完成', context);
                              }, onFail: (error) {
                                errname = error;
                                _focusNodeNotarizePassWord.unfocus();
                                _focusNodeNewPassWord.unfocus();
                                _focusNodePwd.unfocus();
                              });
                            } else {
                              _focusNodeNotarizePassWord.unfocus();
                              _focusNodeNewPassWord.unfocus();
                              _focusNodePwd.unfocus();
                            }
                          },
                        ),
                      )),
                ),
              ],
            ),
          )
        ));
  }
}
